import { _decorator, Collider2D, Contact2DType, Animation, Component, Sprite, log } from 'cc';
const { ccclass, property } = _decorator;
import { PathPoint } from './Utils/PathPoint';
import { PathManager } from './PatheManager';
import { ResourcesManager } from './ResourcesManager';
import { SoundManager } from './SoundManager';

// 在类外部定义方向枚举
enum Direction {
    LEFT = 'LEFT',
    RIGHT = 'RIGHT',
    DOWN = 'DOWN',
    UP = 'UP'
}

@ccclass('Enemy')
export class Enemy extends Component {

    private speed: number = 0.1; // 设置合适的速度值

    private t = 0;

    @property(Number)
    public HP:number = 100;

    private pathManager: PathManager;

    private paths: PathPoint[] = [];

    private collider:Collider2D = null;

    animation:Animation = null;

    @property(Sprite)
    bloodBkSprite:Sprite = null;

    @property(Sprite)
    bloodFillSprite:Sprite = null;

    soundManager:SoundManager = null;

    //转身状态
    private readonly animationState = {
        "front":"toFront",
        "left":"toLeft",
        "right":"toRight",
        "back":"toBack",
        "dead":"dead"
    }

    private lastTurnState:string = "toFront";

    protected start(): void {
        this.soundManager = SoundManager.instance;

        this.animation = this.node.getComponent(Animation);

        this.node.setPosition(-34,442,0);

        (async () => {
            await this.startMove();

            this.collider = this.node.getComponent(Collider2D);
            //设置碰撞器
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onContactEnter, this);
            this.collider.on(Contact2DType.END_CONTACT, this.onContactEnd, this);
        })().catch(err => {
            console.error('Error in start:', err);
        });
    }

    onContactEnter(selfCollider:Collider2D, otherCollider:Collider2D){

    }

    onContactEnd(){

    }


    update(deltaTime: number) {

        //要是start的异步还没好，先不执行后面
        if (!this.pathManager) {
            return;
        }

        if(this.HP <= 0){
            return;
        }

        var turnState = this.pathManager.getCurrTurnState();
        if(turnState){            
            if(turnState != this.lastTurnState){
                this.animation.stop();
                this.lastTurnState = turnState;
                this.animation.play(this.animationState[turnState]);
            }
        }

        //如果走完了路程，销毁敌人
        if (this.pathManager.isCompleted()) {
            this.node.parent.emit("removeEnemy",this.node);
            this.node.destroy();
            return;
        }

        const point = this.pathManager.updatePosition(deltaTime);
        if (point) {            
            this.node.setPosition(point.x, point.y, 0);    
        }

    }


    //加载行走信息
    async getPathData() {
        try {
            const data = await ResourcesManager.instance.loadJson("levelData/PathData");
            return data.json.info;
        } catch (err) {
            console.error("加载失败:", err);
        }
    }



    //敌人开始行走
    async startMove() {
        var roadData = await this.getPathData();

        var path = roadData[0].paths;

        //敌人行走路径
        for (var item of path) {
            this.paths.push(new PathPoint(item.startPos, item.controlPos, item.endPos, item.speed, item.turnState));
        }

        this.pathManager = new PathManager(this.paths);
    }


    //被打中
    takeDamage(damage:number){
        this.HP -= damage;
        this.bloodFillSprite.fillStart = this.HP / 100;
        if(this.HP <= 0){
            this.soundManager.playDeadAudio();
            this.animation.play(this.animationState.dead);

            //死亡动画完成后再销毁敌人
            setTimeout(() => {

                if(this.node!=null){
                    this.node.parent.emit("removeEnemy",this.node);
                    this.node.destroy();
                }
            }, 1300);
        }
    }
}


